/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.list.choose;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;

import twaver.CheckableFilter;
import twaver.DataBoxAdapter;
import twaver.DataBoxEvent;
import twaver.Element;
import twaver.Node;
import twaver.PopupMenuGenerator;
import twaver.TDataBox;
import twaver.TView;
import twaver.TWaverConst;
import twaver.TWaverUtil;
import twaver.VisibleFilter;
import twaver.list.TList;
import twaver.swing.TPopupMenu;
import twaver.swing.TableLayout;
import demo.DemoPane;

public class ChooseDemo extends DemoPane implements ActionListener{

	private TDataBox box1 = new TDataBox("List1");
	private TList list1 = new TList(box1);
	private TDataBox box2 = new TDataBox("List2");
	private TList list2 = new TList(box2);	
	private JPanel controlPane = new JPanel();
	private JButton add = new JButton(">");
	private JButton addAll = new JButton(">>");
	private JButton remove = new JButton("<");
	private JButton removeAll = new JButton("<<");
	private JCheckBox checkSelection = new JCheckBox("Check Selection");
	private JCheckBox disableOddCheck = new JCheckBox("Disable Odd Check");
	private JCheckBox hideEvenItem = new JCheckBox("Hide Even Items");
	private JCheckBox hideItemIcon = new JCheckBox("Hide Item Icon");
	private JCheckBox centerAlignment = new JCheckBox("Center Alignment");
	private JCheckBox selectedWhenChecked = new JCheckBox("Selected When Checked", true);
	
	public ChooseDemo(){		
		this.initControlPane();
		double[] rows = new double[] {
            TableLayout.FILL,
        };
        double[] columns = new double[] {
            TableLayout.FILL,
            TableLayout.PREFERRED,
            TableLayout.FILL,
        };
        TableLayout layout = new TableLayout(columns, rows);
        layout.setVGap(10);
        layout.setHGap(10);        
        this.setLayout(layout);
        this.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        this.add(new JScrollPane(list1), "0,0");
        this.add(controlPane, "1,0");
        this.add(new JScrollPane(list2), "2,0");
        
        
        box1.addDataBoxListener(new DataBoxAdapter(){
            public void elementAdded(DataBoxEvent e){
            	e.getElement().setIcon("/demo/list/choose/offline.gif");
            }
        });
        box2.addDataBoxListener(new DataBoxAdapter(){
            public void elementAdded(DataBoxEvent e){
            	e.getElement().setIcon("/demo/list/choose/online.gif");
            }
        });
        

//		long start = System.currentTimeMillis();
//		list1.setLazyPublishMode(true);
//		box1.startBatch();
//		list1.lock();
        for(int i=0; i<30; i++){
        	Integer id = TWaverUtil.valueOf(i);
        	Node node = new Node(id);
        	node.setName("Item " + i);
        	box1.addElement(node);
        }
//		list1.unlock();
//		box1.endBatch();
//		System.out.println(box1.size() + "|" + (System.currentTimeMillis()-start));
        
        // set sort comparator
        Comparator comparator = new Comparator(){
			public int compare(Object o1, Object o2) {
				Element e1 = (Element)o1;
				Element e2 = (Element)o2;
				Integer id1 = (Integer)e1.getID();
				Integer id2 = (Integer)e2.getID();
				return id1.compareTo(id2);
			}
        };
        list1.setSortComparator(comparator);
        list2.setSortComparator(comparator);
        
        // set checkable filter
        CheckableFilter checkableFilter = new CheckableFilter(){
			public boolean isCheckable(Element element) {
				if(disableOddCheck.isSelected()){
					return ((Integer)element.getID()).intValue() % 2 != 1;	
				}else{
					return true;
				}
			}
        };
        list1.setCheckableFilter(checkableFilter);
        list2.setCheckableFilter(checkableFilter);
        
        // add visible filter
        VisibleFilter visibleFilter = new VisibleFilter(){
			public boolean isVisible(Element element) {
				if(hideEvenItem.isSelected()){
					return ((Integer)element.getID()).intValue() % 2 != 0;	
				}else{
					return true;
				}
			}
        };
        list1.addVisibleFilter(visibleFilter);
        list2.addVisibleFilter(visibleFilter);
        
        // add double click action listener
        ActionListener actionListener = new ActionListener(){
			public void actionPerformed(ActionEvent e) {
                Element element = (Element)e.getSource();
                JOptionPane.showMessageDialog(ChooseDemo.this, "You clicked '" + element.getName() + "'");	
			}
        };
        list1.addElementDoubleClickedActionListener(actionListener);
        list2.addElementDoubleClickedActionListener(actionListener);
        
        // add popup menu generator
        PopupMenuGenerator popupMenuGenerator = new PopupMenuGenerator(){
			public JPopupMenu generate(TView tview, MouseEvent mouseEvent) {
				final TDataBox box = tview.getDataBox();
				if(box.getSelectionModel().size() > 0){
					TPopupMenu popupMenu = new TPopupMenu(box.getName(), Color.RED, Color.WHITE, Color.BLUE, 20);
					JMenuItem item = new JMenuItem("Remove Elements");
					item.addActionListener(new ActionListener(){
						public void actionPerformed(ActionEvent e) {
							box.removeSelectedElements();
						}
					});
					popupMenu.add(item);
					item = new JMenuItem("Clear Selection");
					item.addActionListener(new ActionListener(){
						public void actionPerformed(ActionEvent e) {
							box.getSelectionModel().clearSelection();
						}
					});
					popupMenu.add(item);
					return popupMenu;
				}
				return null;
			}
        };
        list1.setPopupMenuGenerator(popupMenuGenerator);
        list2.setPopupMenuGenerator(popupMenuGenerator);
	}
	
	private JPanel createStylePanel(){
	    JPanel panel = new JPanel(new GridLayout(3, 1));
	    panel.setBorder(BorderFactory.createTitledBorder("Uncheckable Style"));
	    ButtonGroup group = new ButtonGroup();
	    panel.add(createStyleButton("None Style", TWaverConst.UNCHECKABLE_STYLE_NONE, group));
	    panel.add(createStyleButton("Blank Style", TWaverConst.UNCHECKABLE_STYLE_BLANK, group));
	    panel.add(createStyleButton("Disable Style", TWaverConst.UNCHECKABLE_STYLE_DISABLE, group));
	    return panel;
	}
	
	private JRadioButton createStyleButton(String name, final int style, ButtonGroup group){
	    JRadioButton button = new JRadioButton(name);
	    button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				list1.setUncheckableStyle(style);
				list2.setUncheckableStyle(style);
			}
	    });
	    if(list1.getUncheckableStyle() == style){
	    	button.setSelected(true);
	    }
	    group.add(button);
	    return button;
	}
	
	
	private void initControlPane(){
		double[] rows = new double[] {
	    	TableLayout.FILL,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.PREFERRED,
	    	TableLayout.FILL,
	    };
	    double[] columns = new double[] {
	        TableLayout.PREFERRED,
	    };
        TableLayout layout = new TableLayout(columns, rows);
        layout.setVGap(10);
        layout.setHGap(3); 
        controlPane.setLayout(layout);
        controlPane.add(add, "0,1");
        controlPane.add(addAll, "0,2");
        controlPane.add(remove, "0,3");
        controlPane.add(removeAll, "0,4");
        controlPane.add(checkSelection, "0,5");
        controlPane.add(disableOddCheck, "0,6");
        controlPane.add(hideEvenItem, "0,7");
        controlPane.add(hideItemIcon, "0,8");
        controlPane.add(centerAlignment, "0,9");
        controlPane.add(selectedWhenChecked, "0,10");
        controlPane.add(createStylePanel(), "0,11");
        
        add.addActionListener(this);
        addAll.addActionListener(this);
        remove.addActionListener(this);
        removeAll.addActionListener(this);
        checkSelection.addActionListener(this);
        disableOddCheck.addActionListener(this);
        hideEvenItem.addActionListener(this);
        hideItemIcon.addActionListener(this);
        centerAlignment.addActionListener(this);
        selectedWhenChecked.addActionListener(this);
	}

	private void move(List elements, TDataBox source, TDataBox target){
		Iterator it = elements.iterator();
		while(it.hasNext()){
			Element element = (Element)it.next();
			if(!element.isSelected()){
				it.remove();
			}
			source.removeElement(element);
			target.addElement(element);
		}
		if(elements.size() > 0){
			target.getSelectionModel().setSelection(elements);
		}
	}
	
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if(add == source){
			move(box1.getSelectionModel().getAllSelectedElement(), box1, box2);
		}
		else if(addAll == source){
			move(box1.getAllElements(), box1, box2);
		}
		else if(remove == source){
			move(box2.getSelectionModel().getAllSelectedElement(), box2, box1);
		}
		else if(removeAll == source){
			move(box2.getAllElements(), box2, box1);
		}
		else if(checkSelection == source){
			int mode = checkSelection.isSelected() ? TList.CHECK_SELECTION : TList.DEFAULT_SELECTION;
			list1.setTListSelectionMode(mode);
			list2.setTListSelectionMode(mode);
		}
		else if(disableOddCheck == source){
			list1.publishData();
			list2.publishData();
		}
		else if(hideEvenItem == source){
			list1.publishData();
			list2.publishData();
		}
		else if(hideItemIcon == source){
			list1.setIconVisible(!hideItemIcon.isSelected());
			list2.setIconVisible(!hideItemIcon.isSelected());
		}
		else if(centerAlignment == source){
			list1.setCenterAlignment(centerAlignment.isSelected());
			list2.setCenterAlignment(centerAlignment.isSelected());
		}
		else if(selectedWhenChecked == source){
			list1.setPaintSelectedStateWhenChecked(selectedWhenChecked.isSelected());
			list2.setPaintSelectedStateWhenChecked(selectedWhenChecked.isSelected());
		}
		
	}
	
}